<template>
<theme-box title="活动添加">
  <form class="form-inline" @submit.prevent v-el:form>
    <div class="box-body">
      <form-select title="商户号" :required=true name="mchtId" :options="branchList" :value.sync="mchtId"></form-select>
      <!--<div class="customization">-->
        <!--&lt;!&ndash; <form-check-box title="适用商户" :required=true name="mchtIds" :options="mchtIdList" v-if="mchtIdList.length> 0"></form-check-box> &ndash;&gt;-->
      <!--</div>-->
      <form-input title="活动名称" :required=true name="actName"></form-input>
      <form-input title="活动描述" :required=true name="actDsc"></form-input>
      <form-select title="活动类型" :required=true name="actType" :options="actType" :value.sync="actTypeID" :disabled="true" v-el:actType></form-select>
      <form-input title="发券数量" :required=true name="couponNum" number v-ref:coupon @input="couponInput" ></form-input>
      <form-date-time title="活动开始时间" :required=true name="actBegDate" :value.sync="beginTime" :disabled="isRuleListLen" :read-only="true"></form-date-time>
      <form-date-time title="活动结束时间" :required=true name="actEndDate" :value.sync="endTime" :read-only="true"></form-date-time>
      <form-select title="活动模板" :required=true name="modId" :options="modList" :value.sync="modId"></form-select>

      <rule-model v-if="ruleName"
        :rule-list="ruleList"
        :rule-name="ruleName"
        @add-rule="addRule"
        @remove="remove"
        @time-rule="timeRule"
        :txt-date="beginTime + '至' + endTime"
        ></rule-model>
    </div>
    <div class="box-footer">
      <v-button type="reset" @click="reset">重置</v-button>
      <v-button type="submit" theme="primary" class="pull-right">确认</v-button>
    </div>
  </form>

</theme-box>
</template>
<style lang="less">
.customization .col-sm-10.item > div > label {
    width: auto;
}
</style>
<style lang="less" scoped>
.control-label {
    text-align: left!important;
}
</style>
<script>
import RuleModel from './rule'
import 'plugins/jquery-validation'
import {
  dateTime
} from 'ui/collections/general.js'
import {
  deepClone
} from 'lib/clone.js'
import serialize from 'form-serialize'
import FormCheckBox from './checkbox';
export default {
  components: {
    RuleModel,
    FormCheckBox
  },
  data: () => ({
    branchList: [],
    actTypeID: '', // 活动类型ID
    modId: '', // 模板ID
    mchtId: '', // 商户ID
    mchtIdList: [], // 下级商户list
    couponList: [], // 当前商户ID下对应的电子券list
		dishList: [],   // 当前商户ID下对应的菜品
    actType: [ // 活动类型list
      {
        key: "优惠券",
        value: "01"
      },
      {
        key: "打折",
        value: "00"
      },
      {
        key: "储值卡",
        value: "02"
      },
    ],
    beginTime: '',
    endTime: '',
    couponNum:'',
    modList: [], // 当前活动类型ID下对应的模板list
    ruleList: [], // 规则list
    ruleName: '', // 规则名称
    ruleParams: {}, // 添加模板参数,
    isRuleListLen: false,
    timeRuleArr: []
  }),
  watch: {
    actTypeID(newVal) {
      // 获取模板ID list
      if (newVal) {
        this.getModeler(newVal);
      }
    },
    modId(newVal) {
      // 模板详情
      if (newVal) {
        this.modelInfor(newVal)
      }
    },
    mchtId(newVal) {
      if (newVal) {
				this.ruleList = []
        if (this.endTime) {
          let time = this.endTime.split("-").join('')
          this.getCoupons(this.mchtId, time)
        }
				this.queryDish(newVal)
				// this.juniorMchtIds(newVal)
      }
    },
		couponList(newVal) {
			if (newVal) {
				this.modelInfor(this.modId)
			}
		},
    endTime(newVal) {
      if (newVal) {
        this.ruleList = []
        let time = newVal.split("-").join('')
        this.getCoupons(this.mchtId, time)
      }
    },
    ruleList: {
      deep: true,
      handler(value) {
        if (value.length > 0) {
          this.isRuleListLen = true
        } else {
          this.isRuleListLen = false
        }
      }
    }
  },
  // mcht:false,
  methods: {
    timeRule (isError, index) {
      this.timeRuleArr[index] = isError
    },
		queryDish (mchtId) {
      this.$post({
        url: "/api/v2" + projectName_Url + `/plat/dishType/querylow/${mchtId}`,
        method: "GET"
      }).then(res => {
        if (res.content) {
          let data = res.content.lowTypeNameList;
          data.forEach(dish => {
            dish.key = dish.typeName
            dish.value = (dish.typeId).toString()
          })
          this.dishList = data
        }
      })
    },
    couponInput () {
         if (this.mchtId && this.endTime) {
            this.ruleList = [];
            let time = this.endTime.split("-").join('');
            this.getCoupons(this.mchtId, time);
         }
    },
    addRule() {
      if (this.$refs.coupon.value === '') {
          Midway.alert({
         title: "提示",
         content: "请先填写发券数量! "
       })
       return false;
      }
      if (this.endTime && this.beginTime) {
        let list = deepClone(this.ruleParams);
        this.ruleList.push(list);
      } else if (!this.beginTime) {
        Midway.alert({
         title: "提示",
         content: "请先选择活动开始时间！"
       })
      } else if (!this.endTime) {
        Midway.alert({
         title: "提示",
         content: "请先选择活动结束时间！"
       })
      }
    },
    remove(index) {
      this.ruleList.splice(index, 1);
    },
    reset() {
      $("label.error").remove();
      this.$els.form.reset();
    },
    async juniorMchtIds(mchtId) { // 获取下级商户
      let mchtIdList = (await this.$post({
        url: "/api/v2" + projectName_Url + "/plat/mcht/getmchtname/" + mchtId,
        method: "GET"
      })).content
      if (mchtIdList.info) {
        mchtIdList.info.forEach(item => {
          item.key = `${item.mchtId}-${item.mchtName}`
          item.value = `${item.mchtId}`
        })
        this.$set('mchtIdList', mchtIdList.info)
      }
    },
    async getCoupons(mchtId, endTime) { // 获取优惠券
     let couponNum = Number(this.$refs.coupon.value.trim());
     if (couponNum <= 0 ) {
            return false
        }
     let couponList = (await this.$post({
        url: '/api/v2' + projectName_Url + '/plat/mod/querycoupon',
        method: "POST",
        data: {
          mchtId,
          endTime,
          couponNum
        }
      })).content
      if (couponList.allCoupon) {
        let list = couponList.allCoupon.map(item => ({
          key: item.name,
          value: item.couponId
        }))
        this.$set("couponList", list)
      }
    },
    modelInfor(modId) { // 获取规则模板数据
      this.$post({
        url: '/api/v2' + projectName_Url + '/plat/mod/rule/' + modId,
        method: 'GET'
      }).then(response => {
        if (response.content) {
          let ruleList = response.content
          ruleList.conInf.forEach(item => {
            if (item.fldInputMd === '03') {
              item.fldValue = []
            } else if (item.fldDataType === '03') {
              item.fldValue = [
                ['00', '00', '00'],
                ['23', '59', '59']
              ]
            } else {
              item.fldValue = ''
            }
						if (item.fldName === 'fp_type') {
							item.options = this.dishList
						}
          })
          ruleList.conInf.push({
            fldInputMd: '01',
            fldName: ruleList.rsValue,
            fldCname: ruleList.ruleName,
            options: this.couponList,
            fldValue: ''
          })
          this.ruleName = ruleList.ruleName
          this.$set('ruleParams', ruleList)
        }
      })
    },
    getModeler(modType) { // 获取模板
      this.$post({
        url: '/api/v2' + projectName_Url + `/plat/mod/mod/${modType}`,
        method: 'GET'
      }).then(response => {
        if (response.content) {
          let modList = []
          let list = response.content.modTypeList
          list.forEach(item => {
            let value = {
              key: item.modName,
              value: item.modType
            }
            modList.push(value)
          })
          this.$set('modList', modList)
        }
      })
    },
    getBranch() {
      let self = this;
      var mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId
      self.$post({
        url: '/api/v2' + projectName_Url + '/list/mcht/' + mchtId,
        method: "GET"
      }).then(response => {
        if (response) {
          let branchList = [];
          let data = response.content.info
          data.forEach(key => {
            let json = {
              value: key.value,
              key: key.key
            };
            branchList.push(json);
          });
          self.$set("branchList", branchList);
        }
      }, error => {});
    },
    submit(data) {
      let self = this;
      data.actBegDate = data.actBegDate.split('-').join('')
      data.actEndDate = data.actEndDate.split('-').join('')
      let actRule = [{
        modValue: [{
          ruleId: '',
          value: []
        }]
      }]
      let arrValue = actRule[0].modValue
      arrValue[0].ruleId = this.ruleParams.ruleId
      let ruleList = this.ruleList
      // 判断交易时间是否正确
      if (this.timeRuleArr.length > 0) {
        let hasError
        this.timeRuleArr.forEach(isError => {
          if (isError) {
            hasError = true
            return
          }
        })
        if (hasError) {
          return
        }
      }
      for (let i = 0, listLen = ruleList.length; i < listLen; i++) {
        let arr = []
        let ruleItem = ruleList[i].conInf
        for (let z = 0, ruleItemLen = ruleItem.length; z < ruleItemLen; z++) {
					// 判断优惠卷的值是否为空
					if (ruleItem[z].fldName === "coupon") {
						if (!ruleItem[z].fldValue) {
							let data = {
								title: "提示",
								content: "优惠券不能为空！"
							}
							Midway.alert(data)
							return
						}
					}
          // 插入交易日期
          if (ruleItem[z].fldName === "txn_date") {
            ruleItem[z].fldValue = `${data.actBegDate},${data.actEndDate}`
          }
          if (ruleItem[z].fldName !== "fp_type") {
            if (!ruleItem[z].fldValue || ruleItem[z].fldValue.length === 0) {
              let data = {
                title: "提示",
                content: "活动规则每项都是必填！"
              }
              Midway.alert(data)
              return
            }
          }
          if (ruleItem[z].fldValue || ruleItem[z].fldValue.length > 0) {
            let value
            if (ruleItem[z].conFldOpr === '06' && ruleItem[z].fldName !== "txn_date") {
              value = ruleItem[z].fldValue.join(',')
            } else if (ruleItem[z].fldDataType === '03' && ruleItem[z].fldName !== "txn_date") {  // 时间
              value = ruleItem[z].fldValue[0].join('') + ',' + ruleItem[z].fldValue[1].join('')
            } else if (ruleItem[z].fldInputMd === '03') {  // 多选
							let _fldValue = ruleItem[z].fldValue
              value = _fldValue.length === 1? _fldValue[0]: _fldValue.join(',')
            } else {
              value = ruleItem[z].fldValue
            }
            let rule = {
              "fldId": ruleItem[z].fldName,
              "fldValue": value,
              "conFldOpr": ruleItem[z].conFldOpr
            }
            arr.push(rule)
          }
        }
        arrValue[0].value.push({
          [String(i)]: arr
        })
      }
      if (arrValue[0].value.length === 0) {
        let data = {
          title: "提示",
          content: "活动规则不能为空！"
        }
        Midway.alert(data)
        return
      }
      data.actRule1 = JSON.stringify(actRule)
      self.$post({
        url: "/api/v2" + projectName_Url + "/plat/act/add/" + data.mchtId,
        method: "POST",
        data
      }).then(response => {

        let data = {
          title: "操作成功",
          content: "是否查看活动列表?"
        }
        Midway.confirm(data).then(function() {
          self.$route.router.go('/activity/list');
        }).catch(function(e){
          self.ruleList = [];
        })
        self.reset();
      });
    },
  },
  created() {
    this.actTypeID = '01'
    this.getBranch();
    this.getModeler(this.actTypeID);
  },
  ready: function() {
    dateTime({
      format: "yyyy-mm-dd",
      minView: "2"
    })

    let self = this;

    $(this.$els.form).submit(function() {
      return false;
    })
    $(this.$els.form).validate({
      submitHandler: function() {
        let form = this.currentForm;

        $(form).find("input").each(function() {
          $(this).val($.trim($(this).val()));
        });
        let _data = serialize(form, {
          hash: true,
          disabled: true,
          empty: true
        });
        delete _data.money
				delete _data.txn_time_start
				delete _data.txn_time_end
        if (Array.isArray(_data.mchtIds) && _data.mchtIds.length > 1) {
          _data.mchtIds = _data.mchtIds.join(',')
        } else if (!Array.isArray(_data.mchtIds)) {
          _data.mchtIds = _data.mchtIds
        } else {
          _data.mchtIds = ''
        }
         
        self.submit(_data);
      },
      rules: {
        mchtId: {
          required: true,
        },
        couponNum: {
            required: true,
            digits:true,
            number: true
        },
        mchtIds: {
          required: true,
        },
        actName: {
          required: true,
          maxlength:64
        },
        actType: {
          required: true,
        },
        actDsc: {
          required: true,
          maxlength:128
        },
        actBegDate: {
          required: true,
          comparisonBeginDate: ['actBegDate', 'actEndDate']
        },
        actEndDate: {
          required: true,
          comparisonDate: ['actBegDate', 'actEndDate']
        },
        modId: {
          required: true,
        },
				money: {
					intMoney: true
				}
      }
    });

  }
}
</script>
